//
//  myDataBase.m
//  FMDataBase Sample
//
//  Created by QF on 15-7-7.
//  Copyright (c) 2015年 QF. All rights reserved.
//

#import "MyFMDB.h"


@interface DBManager ()

@end

@implementation DBManager

//制作一个my数据库的单例
+(DBManager *)shareDataBase
{
    static DBManager *myDB = nil;
    
    if (myDB == nil)
    {
        myDB = [[super alloc]init];
    }
    
    return myDB;
}

#pragma mark - 数据库操作
//打开数据库
-(NSString*)openDatabase:(NSString*)fileName
{
    NSString* result = @"数据库文件已存在";
    
    //设置 数据库的路径
    NSString *filePath = [NSString stringWithFormat:@"%@/Documents/%@" , NSHomeDirectory(), fileName];
    
    NSFileManager * fileManager = [[NSFileManager alloc]init];
    
    //如果数据库文件不存在，就创建一个
    if(![fileManager fileExistsAtPath:filePath])
    {
        //数据库文件不存在，创建一个
        BOOL bCreateFile = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
        
        result = [NSString stringWithFormat:@"数据库文件不存在,创建一个, 创建结果:%d", bCreateFile ];
    }
    
    //打开数据库
    self.dataBase = [[FMDatabase alloc]initWithPath:filePath];
    
    //如果打开失败,则提示失败
    if (!self.dataBase.open )
    {
        result = @"打开数据库失败";
    }
    
    return result;
}


//创建数据表
-(NSString*)createTable:(NSString*)createTableString
{
    NSString* result;
    
    //创建表添加字段SQL字符串
   //NSString *createTableString = @"create table if not exists order2(serial integer primary key autoincrement, orderno varchar(32), company varchar(32), status varchar(32), updatetime varchar(32), remark varchar(32), goods varchar(32), from2 varchar(32), to2 varchar(32), logs varchar(32), photo varchar(32))" ;
    
    //创建表
    BOOL bCreateTable = [self.dataBase executeUpdate:createTableString];
    
    result = [NSString stringWithFormat:@"数据表创建结果:%d", bCreateTable];
    
    return result;
}

//删除数据表
-(NSString*)dropTable:(NSString*)dropTableName
{
    NSString * result;
    
    NSString * dropTableString = [NSString stringWithFormat:@"drop table if exists %@",dropTableName];
    
    BOOL bDropTable = [self.dataBase executeUpdate:dropTableString];
    
    result = [NSString  stringWithFormat:@"删除数据表结果:%d", bDropTable];
    
    return result;
}


//将数据表清空
-(NSString*)deleteTable:(NSString*)deleteTableName
{
    NSString * result;
    
    NSString * deleteTableString = [NSString stringWithFormat:@"delete from %@",deleteTableName];
    
    BOOL bDeleteTable = [self.dataBase executeUpdate:deleteTableString];
    
    result = [NSString  stringWithFormat:@"删除数据表结果:%d", bDeleteTable];
    
    return result;
}

@end

